package com.example.demo.service;

import com.example.demo.entity.Book;
import com.example.demo.mapper.BookMapper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class BookService {
    
    @Autowired
    private BookMapper bookMapper;
    
    public List<Book> findAll() {
        return bookMapper.findAll();
    }
    
    public Book findById(Long id) {
        return bookMapper.findById(id);
    }
    
    public Book save(Book book) {
        if (book.getId() == null) {
            // 新增图书
            bookMapper.insert(book);
        } else {
            // 更新图书
            Book existingBook = bookMapper.findById(book.getId());
            if (existingBook == null) {
                throw new RuntimeException("图书不存在：" + book.getId());
            }
            bookMapper.update(book);
        }
        return book;
    }
    
    public void delete(Long id) {
        Book existingBook = bookMapper.findById(id);
        if (existingBook == null) {
            throw new RuntimeException("图书不存在：" + id);
        }
        bookMapper.delete(id);
    }
    
    public byte[] exportToExcel() throws IOException {
        List<Book> books = bookMapper.findAll();
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Books");
        
        // 创建表头
        XSSFRow headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("书名");
        headerRow.createCell(2).setCellValue("作者");
        headerRow.createCell(3).setCellValue("出版社");
        headerRow.createCell(4).setCellValue("价格");
        headerRow.createCell(5).setCellValue("库存");
        
        // 填充数据
        int rowNum = 1;
        for (Book book : books) {
            XSSFRow row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(book.getId());
            row.createCell(1).setCellValue(book.getName());
            row.createCell(2).setCellValue(book.getAuthor());
            row.createCell(3).setCellValue(book.getPublisher());
            row.createCell(4).setCellValue(book.getPrice());
            row.createCell(5).setCellValue(book.getStock());
        }
        
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();
        
        return outputStream.toByteArray();
    }
} 